<!--上传文件-->
<template>
  <el-upload
    class="upload-demo"
    v-model="value"
    v-bind="$attrs"
    :id="'c' + meta.columnId"
    :name="'c' + meta.columnId"
    :accept="myAccept"
    :action="action"
    :on-preview="handlePreview"
    :on-remove="handleRemove"
    :on-change="myChange"
    :before-remove="beforeRemove"
    :on-exceed="handleExceed"
    :file-list="fileList"
  >
    <el-button type="primary">点击选择文件</el-button>
    <template #tip>
      <div class="el-upload__tip">
        文件大小不能超过 500KB
      </div>
    </template>
  </el-upload>
</template>

<script setup lang="ts" generic="T extends object">
  import { reactive, computed } from 'vue'
  import { ElMessageBox, ElMessage } from 'element-plus'
  import type { IFormChildProps } from '../map'
  import { itemController, EControlType } from '../map'

  defineOptions({
    name: 'nf-el-form-item-upload-file',
    inheritAttrs: false,
  })

  const props = withDefaults(defineProps<IFormChildProps<T> & {
    accept?: string,
    action?: string
  }>(), {
    meta: () => {
      return {
        colName: '',
        controlType: EControlType.file
      }
    },
    model: () => {
      return {} as T
    },
    accept: '',
    suffixIcon: 'https://aaa.com/posts/'
  })
  
  // console.log('props-text', props)
  const { value } = itemController(props)

  // 转换允许上传的类型
  const myAccept = computed(() => {
    if (Array.isArray(props.accept)) {
      return props.accept.join(',')
    } else {
      return props.accept
    }
  })

  const fileList = reactive([
    {
      name: 'food.jpeg',
      url: 'https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100',
    },
    {
      name: 'food2.jpeg',
      url: 'https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100',
    },
  ])

  // 重新选择文件
  const myChange = (file, fileList) => {
    console.log(file, fileList)
  }

  // 删除文件
  const handleRemove = (file, fileList) => {
    console.log(file, fileList)
  }
  const beforeRemove = (file, fileList) => {
    return ElMessageBox.confirm(`真的要删除 ${file.name} 文件吗？`)
  }
  
  const handlePreview = (file) => {
    console.log(file)
  }
  const handleExceed = (files, fileList) => {
    ElMessage.warning(
      `一次只能同时上传 3 个文件, 您选择的文件数量 ${files.length} 超出限制，
      ${files.length + fileList.length} `
    )
  }
    
</script>
